"""EDA分析报告生成工具

提供多种格式的EDA分析报告生成功能，支持：
- PDF报告生成
- Word文档报告
- Excel数据报告
- 批量报告汇总
- 自定义模板支持

主要类和函数：
- ReportGenerator: 报告生成器类
- generate_pdf_report: 生成PDF报告
- generate_excel_report: 生成Excel报告
- generate_batch_summary: 生成批量汇总报告
"""

import os
import json
import logging
from pathlib import Path
from typing import Dict, Any, List, Optional, Union
import pandas as pd
import numpy as np
from datetime import datetime
import base64
from io import BytesIO

logger = logging.getLogger(__name__)

# 可选依赖导入
try:
    from reportlab.lib.pagesizes import letter, A4
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.units import inch
    from reportlab.lib import colors
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    REPORTLAB_AVAILABLE = True
except ImportError:
    REPORTLAB_AVAILABLE = False

try:
    from docx import Document
    from docx.shared import Inches
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    PYTHON_DOCX_AVAILABLE = True
except ImportError:
    PYTHON_DOCX_AVAILABLE = False

class ReportGenerator:
    """EDA分析报告生成器"""
    
    def __init__(self, 
                 template_dir: str = None,
                 output_format: str = 'pdf',
                 include_plots: bool = True,
                 language: str = 'zh'):
        """初始化报告生成器
        
        Args:
            template_dir: 模板目录路径
            output_format: 输出格式 ('pdf', 'docx', 'excel', 'html')
            include_plots: 是否包含图表
            language: 语言设置 ('zh', 'en')
        """
        self.template_dir = Path(template_dir) if template_dir else None
        self.output_format = output_format.lower()
        self.include_plots = include_plots
        self.language = language
        
        # 检查依赖
        if self.output_format == 'pdf' and not REPORTLAB_AVAILABLE:
            logger.error("PDF报告需要安装reportlab库")
            raise ImportError("需要安装reportlab库: pip install reportlab")
        
        if self.output_format == 'docx' and not PYTHON_DOCX_AVAILABLE:
            logger.error("Word报告需要安装python-docx库")
            raise ImportError("需要安装python-docx库: pip install python-docx")
        
        # 设置样式
        self._setup_styles()
    
    def _setup_styles(self):
        """设置报告样式"""
        if self.output_format == 'pdf' and REPORTLAB_AVAILABLE:
            # 注册中文字体（如果可用）
            try:
                # 尝试注册系统中文字体
                font_paths = [
                    'C:/Windows/Fonts/msyh.ttc',  # 微软雅黑
                    'C:/Windows/Fonts/simsun.ttc',  # 宋体
                    '/System/Library/Fonts/PingFang.ttc',  # macOS
                    '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'  # Linux
                ]
                
                for font_path in font_paths:
                    if os.path.exists(font_path):
                        pdfmetrics.registerFont(TTFont('ChineseFont', font_path))
                        break
            except Exception as e:
                logger.warning(f"无法注册中文字体: {e}")
    
    def generate_report(self,
                       eda_data: Dict[str, Any],
                       results: Dict[str, Any],
                       output_path: str,
                       title: str = None,
                       author: str = None,
                       plots_dir: str = None) -> bool:
        """生成分析报告
        
        Args:
            eda_data: EDA数据字典
            results: 处理结果字典
            output_path: 输出文件路径
            title: 报告标题
            author: 报告作者
            plots_dir: 图表目录路径
            
        Returns:
            生成是否成功
        """
        try:
            if self.output_format == 'pdf':
                return self._generate_pdf_report(eda_data, results, output_path, title, author, plots_dir)
            elif self.output_format == 'docx':
                return self._generate_docx_report(eda_data, results, output_path, title, author, plots_dir)
            elif self.output_format == 'excel':
                return self._generate_excel_report(eda_data, results, output_path, title)
            elif self.output_format == 'html':
                return self._generate_html_report(eda_data, results, output_path, title, plots_dir)
            else:
                logger.error(f"不支持的输出格式: {self.output_format}")
                return False
                
        except Exception as e:
            logger.error(f"生成报告失败: {str(e)}")
            return False
    
    def _generate_pdf_report(self, eda_data, results, output_path, title, author, plots_dir):
        """生成PDF报告"""
        doc = SimpleDocTemplate(output_path, pagesize=A4)
        story = []
        styles = getSampleStyleSheet()
        
        # 创建自定义样式
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=styles['Heading1'],
            fontSize=18,
            spaceAfter=30,
            alignment=1  # 居中
        )
        
        heading_style = ParagraphStyle(
            'CustomHeading',
            parent=styles['Heading2'],
            fontSize=14,
            spaceAfter=12
        )
        
        # 标题
        report_title = title or "EDA数据分析报告"
        story.append(Paragraph(report_title, title_style))
        story.append(Spacer(1, 12))
        
        # 基本信息
        if author:
            story.append(Paragraph(f"作者: {author}", styles['Normal']))
        story.append(Paragraph(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", styles['Normal']))
        story.append(Spacer(1, 20))
        
        # 数据概览
        story.append(Paragraph("数据概览", heading_style))
        
        signal_length = len(eda_data['signal'])
        sampling_rate = eda_data.get('sampling_rate', 4.0)
        duration = signal_length / sampling_rate
        
        overview_data = [
            ['项目', '数值'],
            ['信号长度', f"{signal_length} 个采样点"],
            ['采样率', f"{sampling_rate} Hz"],
            ['信号时长', f"{duration:.2f} 秒"],
            ['数据质量', f"{results.get('quality_assessment', {}).get('overall_score', 0.0):.2f}"]
        ]
        
        overview_table = Table(overview_data)
        overview_table.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 14),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
            ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
            ('GRID', (0, 0), (-1, -1), 1, colors.black)
        ]))
        
        story.append(overview_table)
        story.append(Spacer(1, 20))
        
        # 分析指标
        if 'metrics' in results:
            story.append(Paragraph("分析指标", heading_style))
            
            metrics_data = [['指标名称', '数值', '单位']]
            for key, value in results['metrics'].items():
                if isinstance(value, (int, float)):
                    metrics_data.append([key, f"{value:.4f}", "-"])
            
            metrics_table = Table(metrics_data)
            metrics_table.setStyle(TableStyle([
                ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                ('FONTSIZE', (0, 0), (-1, 0), 12),
                ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
                ('GRID', (0, 0), (-1, -1), 1, colors.black)
            ]))
            
            story.append(metrics_table)
            story.append(Spacer(1, 20))
        
        # 峰值检测结果
        if 'peaks' in results and results['peaks']:
            story.append(Paragraph("峰值检测结果", heading_style))
            
            peak_count = len(results['peaks'])
            story.append(Paragraph(f"检测到 {peak_count} 个SCR峰值", styles['Normal']))
            
            # 峰值统计
            if peak_count > 0:
                amplitudes = [p.get('amplitude', 0) for p in results['peaks']]
                durations = [p.get('duration', 0) for p in results['peaks']]
                
                peak_stats_data = [
                    ['统计项', '数值'],
                    ['峰值数量', str(peak_count)],
                    ['平均幅度', f"{np.mean(amplitudes):.4f}"],
                    ['平均持续时间', f"{np.mean(durations):.2f} 秒"]
                ]
                
                peak_stats_table = Table(peak_stats_data)
                peak_stats_table.setStyle(TableStyle([
                    ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                    ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                    ('FONTSIZE', (0, 0), (-1, 0), 12),
                    ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                    ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
                    ('GRID', (0, 0), (-1, -1), 1, colors.black)
                ]))
                
                story.append(peak_stats_table)
            
            story.append(Spacer(1, 20))
        
        # 添加图表
        if self.include_plots and plots_dir:
            plots_path = Path(plots_dir)
            
            # EDA信号图
            signal_plot = plots_path / "eda_signal.png"
            if signal_plot.exists():
                story.append(Paragraph("EDA信号", heading_style))
                img = Image(str(signal_plot), width=6*inch, height=4*inch)
                story.append(img)
                story.append(Spacer(1, 20))
            
            # 峰值检测图
            peaks_plot = plots_path / "peak_detection.png"
            if peaks_plot.exists():
                story.append(Paragraph("峰值检测", heading_style))
                img = Image(str(peaks_plot), width=6*inch, height=4*inch)
                story.append(img)
                story.append(Spacer(1, 20))
        
        # 构建PDF
        doc.build(story)
        logger.info(f"PDF报告生成成功: {output_path}")
        return True
    
    def _generate_docx_report(self, eda_data, results, output_path, title, author, plots_dir):
        """生成Word文档报告"""
        doc = Document()
        
        # 标题
        report_title = title or "EDA数据分析报告"
        title_para = doc.add_heading(report_title, 0)
        title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
        
        # 基本信息
        if author:
            doc.add_paragraph(f"作者: {author}")
        doc.add_paragraph(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        doc.add_paragraph()
        
        # 数据概览
        doc.add_heading('数据概览', level=1)
        
        signal_length = len(eda_data['signal'])
        sampling_rate = eda_data.get('sampling_rate', 4.0)
        duration = signal_length / sampling_rate
        
        overview_table = doc.add_table(rows=5, cols=2)
        overview_table.style = 'Table Grid'
        
        overview_data = [
            ['项目', '数值'],
            ['信号长度', f"{signal_length} 个采样点"],
            ['采样率', f"{sampling_rate} Hz"],
            ['信号时长', f"{duration:.2f} 秒"],
            ['数据质量', f"{results.get('quality_assessment', {}).get('overall_score', 0.0):.2f}"]
        ]
        
        for i, (key, value) in enumerate(overview_data):
            overview_table.cell(i, 0).text = key
            overview_table.cell(i, 1).text = value
        
        doc.add_paragraph()
        
        # 分析指标
        if 'metrics' in results:
            doc.add_heading('分析指标', level=1)
            
            metrics = results['metrics']
            metrics_table = doc.add_table(rows=len(metrics)+1, cols=3)
            metrics_table.style = 'Table Grid'
            
            # 表头
            metrics_table.cell(0, 0).text = '指标名称'
            metrics_table.cell(0, 1).text = '数值'
            metrics_table.cell(0, 2).text = '单位'
            
            # 数据行
            row_idx = 1
            for key, value in metrics.items():
                if isinstance(value, (int, float)):
                    metrics_table.cell(row_idx, 0).text = key
                    metrics_table.cell(row_idx, 1).text = f"{value:.4f}"
                    metrics_table.cell(row_idx, 2).text = "-"
                    row_idx += 1
            
            doc.add_paragraph()
        
        # 峰值检测结果
        if 'peaks' in results and results['peaks']:
            doc.add_heading('峰值检测结果', level=1)
            
            peak_count = len(results['peaks'])
            doc.add_paragraph(f"检测到 {peak_count} 个SCR峰值")
            
            if peak_count > 0:
                amplitudes = [p.get('amplitude', 0) for p in results['peaks']]
                durations = [p.get('duration', 0) for p in results['peaks']]
                
                peak_stats_table = doc.add_table(rows=4, cols=2)
                peak_stats_table.style = 'Table Grid'
                
                peak_stats_data = [
                    ['统计项', '数值'],
                    ['峰值数量', str(peak_count)],
                    ['平均幅度', f"{np.mean(amplitudes):.4f}"],
                    ['平均持续时间', f"{np.mean(durations):.2f} 秒"]
                ]
                
                for i, (key, value) in enumerate(peak_stats_data):
                    peak_stats_table.cell(i, 0).text = key
                    peak_stats_table.cell(i, 1).text = value
            
            doc.add_paragraph()
        
        # 添加图表
        if self.include_plots and plots_dir:
            plots_path = Path(plots_dir)
            
            # EDA信号图
            signal_plot = plots_path / "eda_signal.png"
            if signal_plot.exists():
                doc.add_heading('EDA信号', level=1)
                doc.add_picture(str(signal_plot), width=Inches(6))
                doc.add_paragraph()
            
            # 峰值检测图
            peaks_plot = plots_path / "peak_detection.png"
            if peaks_plot.exists():
                doc.add_heading('峰值检测', level=1)
                doc.add_picture(str(peaks_plot), width=Inches(6))
                doc.add_paragraph()
        
        # 保存文档
        doc.save(output_path)
        logger.info(f"Word报告生成成功: {output_path}")
        return True
    
    def _generate_excel_report(self, eda_data, results, output_path, title):
        """生成Excel报告"""
        with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
            
            # 概览工作表
            overview_data = {
                '项目': ['信号长度', '采样率', '信号时长', '数据质量'],
                '数值': [
                    len(eda_data['signal']),
                    eda_data.get('sampling_rate', 4.0),
                    len(eda_data['signal']) / eda_data.get('sampling_rate', 4.0),
                    results.get('quality_assessment', {}).get('overall_score', 0.0)
                ],
                '单位': ['个采样点', 'Hz', '秒', '分数']
            }
            
            overview_df = pd.DataFrame(overview_data)
            overview_df.to_excel(writer, sheet_name='概览', index=False)
            
            # 分析指标工作表
            if 'metrics' in results:
                metrics_data = []
                for key, value in results['metrics'].items():
                    if isinstance(value, (int, float)):
                        metrics_data.append({'指标名称': key, '数值': value, '单位': '-'})
                
                if metrics_data:
                    metrics_df = pd.DataFrame(metrics_data)
                    metrics_df.to_excel(writer, sheet_name='分析指标', index=False)
            
            # 峰值检测工作表
            if 'peaks' in results and results['peaks']:
                peaks_data = []
                for i, peak in enumerate(results['peaks']):
                    peak_info = {
                        '峰值编号': i + 1,
                        '起始时间': peak.get('onset_time', 0),
                        '峰值时间': peak.get('peak_time', 0),
                        '恢复时间': peak.get('recovery_time', 0),
                        '幅度': peak.get('amplitude', 0),
                        '持续时间': peak.get('duration', 0)
                    }
                    peaks_data.append(peak_info)
                
                peaks_df = pd.DataFrame(peaks_data)
                peaks_df.to_excel(writer, sheet_name='峰值检测', index=False)
            
            # 质量评估工作表
            if 'quality_assessment' in results:
                quality_data = []
                for key, value in results['quality_assessment'].items():
                    if isinstance(value, (int, float)):
                        quality_data.append({'质量指标': key, '分数': value})
                
                if quality_data:
                    quality_df = pd.DataFrame(quality_data)
                    quality_df.to_excel(writer, sheet_name='质量评估', index=False)
        
        logger.info(f"Excel报告生成成功: {output_path}")
        return True
    
    def _generate_html_report(self, eda_data, results, output_path, title, plots_dir):
        """生成HTML报告"""
        html_content = self._create_html_template(eda_data, results, title, plots_dir)
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        logger.info(f"HTML报告生成成功: {output_path}")
        return True
    
    def _create_html_template(self, eda_data, results, title, plots_dir):
        """创建HTML模板"""
        report_title = title or "EDA数据分析报告"
        
        # 基本信息
        signal_length = len(eda_data['signal'])
        sampling_rate = eda_data.get('sampling_rate', 4.0)
        duration = signal_length / sampling_rate
        quality_score = results.get('quality_assessment', {}).get('overall_score', 0.0)
        
        # 图表部分
        plots_html = ""
        if self.include_plots and plots_dir:
            plots_path = Path(plots_dir)
            
            # EDA信号图
            signal_plot = plots_path / "eda_signal.png"
            if signal_plot.exists():
                plots_html += f"""
                <div class="section">
                    <h2>EDA信号</h2>
                    <div class="plot">
                        <img src="{signal_plot.name}" alt="EDA信号图" style="max-width: 100%; height: auto;">
                    </div>
                </div>
                """
            
            # 峰值检测图
            peaks_plot = plots_path / "peak_detection.png"
            if peaks_plot.exists():
                peak_count = len(results.get('peaks', []))
                plots_html += f"""
                <div class="section">
                    <h2>峰值检测结果</h2>
                    <p>检测到 <strong>{peak_count}</strong> 个SCR峰值</p>
                    <div class="plot">
                        <img src="{peaks_plot.name}" alt="峰值检测图" style="max-width: 100%; height: auto;">
                    </div>
                </div>
                """
        
        # 指标表格
        metrics_table = ""
        if 'metrics' in results:
            metrics_table = "<table><tr><th>指标名称</th><th>数值</th><th>单位</th></tr>"
            for key, value in results['metrics'].items():
                if isinstance(value, (int, float)):
                    metrics_table += f"<tr><td>{key}</td><td>{value:.4f}</td><td>-</td></tr>"
            metrics_table += "</table>"
        
        html_template = f"""
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>{report_title}</title>
            <style>
                body {{ font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 20px; line-height: 1.6; }}
                .header {{ text-align: center; color: #2c3e50; margin-bottom: 30px; }}
                .section {{ margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 8px; background: #f9f9f9; }}
                .metrics {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }}
                .metric {{ background: #fff; padding: 15px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
                .metric strong {{ color: #2c3e50; }}
                .plot {{ text-align: center; margin: 20px 0; }}
                table {{ width: 100%; border-collapse: collapse; margin: 15px 0; }}
                th, td {{ border: 1px solid #ddd; padding: 12px; text-align: left; }}
                th {{ background-color: #3498db; color: white; font-weight: bold; }}
                tr:nth-child(even) {{ background-color: #f2f2f2; }}
                h1 {{ color: #2c3e50; }}
                h2 {{ color: #34495e; border-bottom: 2px solid #3498db; padding-bottom: 5px; }}
            </style>
        </head>
        <body>
            <div class="header">
                <h1>{report_title}</h1>
                <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
            </div>
            
            <div class="section">
                <h2>数据概览</h2>
                <div class="metrics">
                    <div class="metric">
                        <strong>信号长度:</strong> {signal_length} 个采样点
                    </div>
                    <div class="metric">
                        <strong>采样率:</strong> {sampling_rate} Hz
                    </div>
                    <div class="metric">
                        <strong>信号时长:</strong> {duration:.2f} 秒
                    </div>
                    <div class="metric">
                        <strong>质量评分:</strong> {quality_score:.2f}
                    </div>
                </div>
            </div>
            
            {plots_html}
            
            <div class="section">
                <h2>分析指标</h2>
                {metrics_table if metrics_table else '<p>无可用指标</p>'}
            </div>
            
        </body>
        </html>
        """
        
        return html_template
    
    def generate_batch_summary(self,
                              batch_results: List[Dict[str, Any]],
                              output_path: str,
                              title: str = "EDA批量分析汇总报告") -> bool:
        """生成批量分析汇总报告
        
        Args:
            batch_results: 批量处理结果列表
            output_path: 输出文件路径
            title: 报告标题
            
        Returns:
            生成是否成功
        """
        try:
            if self.output_format == 'excel':
                return self._generate_batch_excel_summary(batch_results, output_path, title)
            elif self.output_format == 'html':
                return self._generate_batch_html_summary(batch_results, output_path, title)
            else:
                logger.error(f"批量汇总不支持格式: {self.output_format}")
                return False
                
        except Exception as e:
            logger.error(f"生成批量汇总报告失败: {str(e)}")
            return False
    
    def _generate_batch_excel_summary(self, batch_results, output_path, title):
        """生成Excel格式的批量汇总报告"""
        with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
            
            # 汇总统计
            summary_data = {
                '项目': ['总文件数', '成功处理', '处理失败', '成功率'],
                '数值': [
                    len(batch_results),
                    sum(1 for r in batch_results if r.get('success', False)),
                    sum(1 for r in batch_results if not r.get('success', False)),
                    sum(1 for r in batch_results if r.get('success', False)) / len(batch_results) * 100 if batch_results else 0
                ],
                '单位': ['个', '个', '个', '%']
            }
            
            summary_df = pd.DataFrame(summary_data)
            summary_df.to_excel(writer, sheet_name='汇总统计', index=False)
            
            # 详细结果
            if batch_results:
                detailed_data = []
                for result in batch_results:
                    if result.get('success', False):
                        detailed_data.append({
                            '文件名': result.get('file_name', ''),
                            '处理状态': '成功',
                            '信号长度': result.get('signal_length', 0),
                            '信号时长': result.get('signal_duration', 0),
                            '质量评分': result.get('quality_score', 0),
                            'SCR数量': result.get('scr_count', 0),
                            '平均EDA': result.get('mean_eda', 0),
                            '处理时间': result.get('processing_time', 0)
                        })
                    else:
                        detailed_data.append({
                            '文件名': result.get('file_name', ''),
                            '处理状态': '失败',
                            '错误信息': result.get('error', ''),
                            '信号长度': 0,
                            '信号时长': 0,
                            '质量评分': 0,
                            'SCR数量': 0,
                            '平均EDA': 0,
                            '处理时间': 0
                        })
                
                detailed_df = pd.DataFrame(detailed_data)
                detailed_df.to_excel(writer, sheet_name='详细结果', index=False)
        
        logger.info(f"批量Excel汇总报告生成成功: {output_path}")
        return True
    
    def _generate_batch_html_summary(self, batch_results, output_path, title):
        """生成HTML格式的批量汇总报告"""
        # 计算统计信息
        total_files = len(batch_results)
        successful = sum(1 for r in batch_results if r.get('success', False))
        failed = total_files - successful
        success_rate = (successful / total_files * 100) if total_files > 0 else 0
        
        # 生成详细表格
        results_table = "<table><tr><th>文件名</th><th>状态</th><th>质量评分</th><th>SCR数量</th><th>处理时间</th></tr>"
        
        for result in batch_results:
            if result.get('success', False):
                results_table += f"""
                <tr>
                    <td>{result.get('file_name', '')}</td>
                    <td style="color: green;">成功</td>
                    <td>{result.get('quality_score', 0):.2f}</td>
                    <td>{result.get('scr_count', 0)}</td>
                    <td>{result.get('processing_time', 0):.2f}s</td>
                </tr>
                """
            else:
                results_table += f"""
                <tr>
                    <td>{result.get('file_name', '')}</td>
                    <td style="color: red;">失败</td>
                    <td>-</td>
                    <td>-</td>
                    <td>-</td>
                </tr>
                """
        
        results_table += "</table>"
        
        html_content = f"""
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>{title}</title>
            <style>
                body {{ font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 20px; line-height: 1.6; }}
                .header {{ text-align: center; color: #2c3e50; margin-bottom: 30px; }}
                .section {{ margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 8px; background: #f9f9f9; }}
                .stats {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }}
                .stat {{ background: #fff; padding: 15px; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); text-align: center; }}
                .stat-value {{ font-size: 2em; font-weight: bold; color: #3498db; }}
                .stat-label {{ color: #7f8c8d; }}
                table {{ width: 100%; border-collapse: collapse; margin: 15px 0; }}
                th, td {{ border: 1px solid #ddd; padding: 12px; text-align: left; }}
                th {{ background-color: #3498db; color: white; font-weight: bold; }}
                tr:nth-child(even) {{ background-color: #f2f2f2; }}
                h1 {{ color: #2c3e50; }}
                h2 {{ color: #34495e; border-bottom: 2px solid #3498db; padding-bottom: 5px; }}
            </style>
        </head>
        <body>
            <div class="header">
                <h1>{title}</h1>
                <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
            </div>
            
            <div class="section">
                <h2>处理统计</h2>
                <div class="stats">
                    <div class="stat">
                        <div class="stat-value">{total_files}</div>
                        <div class="stat-label">总文件数</div>
                    </div>
                    <div class="stat">
                        <div class="stat-value">{successful}</div>
                        <div class="stat-label">成功处理</div>
                    </div>
                    <div class="stat">
                        <div class="stat-value">{failed}</div>
                        <div class="stat-label">处理失败</div>
                    </div>
                    <div class="stat">
                        <div class="stat-value">{success_rate:.1f}%</div>
                        <div class="stat-label">成功率</div>
                    </div>
                </div>
            </div>
            
            <div class="section">
                <h2>详细结果</h2>
                {results_table}
            </div>
            
        </body>
        </html>
        """
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        logger.info(f"批量HTML汇总报告生成成功: {output_path}")
        return True

# 便捷函数
def generate_pdf_report(eda_data: Dict[str, Any],
                       results: Dict[str, Any],
                       output_path: str,
                       **kwargs) -> bool:
    """生成PDF报告的便捷函数"""
    generator = ReportGenerator(output_format='pdf', **kwargs)
    return generator.generate_report(eda_data, results, output_path)

def generate_excel_report(eda_data: Dict[str, Any],
                         results: Dict[str, Any],
                         output_path: str,
                         **kwargs) -> bool:
    """生成Excel报告的便捷函数"""
    generator = ReportGenerator(output_format='excel', **kwargs)
    return generator.generate_report(eda_data, results, output_path)

def generate_batch_summary(batch_results: List[Dict[str, Any]],
                          output_path: str,
                          format: str = 'excel',
                          **kwargs) -> bool:
    """生成批量汇总报告的便捷函数"""
    generator = ReportGenerator(output_format=format, **kwargs)
    return generator.generate_batch_summary(batch_results, output_path)


def generate_report(eda_data: Dict[str, Any],
                   results: Dict[str, Any],
                   output_path: str,
                   format: str = 'pdf',
                   **kwargs) -> bool:
    """生成分析报告的通用便捷函数
    
    Args:
        eda_data: EDA数据字典
        results: 处理结果字典
        output_path: 输出文件路径
        format: 输出格式 ('pdf', 'docx', 'excel', 'html')
        **kwargs: 额外的报告生成参数
        
    Returns:
        生成是否成功
    """
    try:
        generator = ReportGenerator(output_format=format, **kwargs)
        return generator.generate_report(eda_data, results, output_path, **kwargs)
    except Exception as e:
        logger.error(f"生成报告失败: {str(e)}")
        return False